package com.yinuo.controller;

import com.alibaba.fastjson.JSON;
import com.yinuo.common.*;
import com.yinuo.entity.GlobalContext;
import com.yinuo.entity.JavaCommonClass;
import com.yinuo.entity.PageJson;
import com.yinuo.repository.JavaRepository;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.io.*;
import java.util.*;

/**
 * Created by gt.ao on 2018/9/25.
 */
@RestController
@RequestMapping("java")
public class JavaController {
    private static Logger logger = LoggerFactory.getLogger(JavaController.class);

    @Autowired
    private JavaRepository javaRepository;

    @RequestMapping("javaCommonQuery")
    public PageJson commonQuery(String keyword) {
        PageJson res = new PageJson();
        List<JavaCommonClass> jdata = null;
        if(!StringUtils.isEmpty(keyword)){
            jdata = javaRepository.findAll(new Specification<JavaCommonClass>() {
                @Override
                public Predicate toPredicate(Root<JavaCommonClass> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                    List<Predicate> predicateList = new ArrayList<>();
                    Predicate p1 = criteriaBuilder.like(criteriaBuilder.upper(root.get("DESC").as(String.class)), "%" + keyword.toUpperCase() + "%");
                    predicateList.add(p1);
                    Predicate[] pre = new Predicate[predicateList.size()];
                    return criteriaQuery.where(predicateList.toArray(pre)).getRestriction();
                }
            });
        }else{
             jdata = javaRepository.findAll();
        }

        res.setTotal(jdata.size());
        for (int i = 0; i < jdata.size(); i++) {
            JavaCommonClass j = jdata.get(i);
            j.setPATH(SystemWaiter.getFilesRootPath() + j.getPATH());
        }
        res.setData(jdata);
        return res;
    }

    @RequestMapping("javaFileUpload")
    public String uploadFile(@RequestParam("txt_file") MultipartFile txt_file) {
        String fileName = txt_file.getOriginalFilename();
        String filePath = GlobalContext.JAVA_COMMON_TOOLS_PATH + fileName;
        JavaCommonClass jcc = new JavaCommonClass();
        jcc.setID(UUIDUtil.UUID32());
        jcc.setPATH(filePath);
        jcc.setDESC("未填写描述");
        jcc.setFILENAME(fileName);
        jcc.setINTIME(DateUtil.getFullDate());
        jcc.setREMARK("");
        try {
            javaRepository.save(jcc);
            String writePath = SystemWaiter.getFilesRootPath() + filePath;
            File file = new File(writePath);
            FileUtils.copyInputStreamToFile(txt_file.getInputStream(),file);
            return JsonResult.toSuccess("上传成功！");
        } catch (Exception e) {
            logger.error(e.getMessage());
            return JsonResult.toFaild();
        }
    }

    @RequestMapping("openFile")
    public String openFile(String path){
        SystemWaiter.openBrowser("file://"+path);
        return JsonResult.toSuccess();
    }

    @RequestMapping("saveDesc")
    @Transactional
    public String saveDesc(String id,String value){
        javaRepository.updateDesc(id,value);
        return "";
    }

    @RequestMapping("javaClsDel")
    public String javaClsDel(String id){
        try {
            Optional<JavaCommonClass> jcontainer = javaRepository.findById(id);
            JavaCommonClass jc = jcontainer.get();
            String path = jc.getPATH();
            path = SystemWaiter.getFilesRootPath()+path;
            if(FileUtil.deleteFile(path)){
                javaRepository.deleteById(id);
                System.out.println("[*删除文件*]："+path);
                return JsonResult.toSuccess();
            }else{
                return JsonResult.toFaild();
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            return JsonResult.toFaild();
        }
    }

    @RequestMapping("springDocNames")
    public String springDocNames(){
        List<Map<String,String>> result = new ArrayList<Map<String,String>>(20);
        Map<String,String> rmap = null;
        String rootPath = SystemWaiter.getFilesRootPath();
        List<String> files = FileUtil.getAllFileNamesByPath(rootPath+GlobalContext.JAVA_DOCUMENTS_PATH);
        for(String s:files){
            rmap = new HashMap<>(3);
            rmap.put("imgUrl",getUrl(s));
            rmap.put("fileName",s);
            rmap.put("filePath",SystemWaiter.getFilesRootPath()+"modular/java/springDocuments/"+s);
            result.add(rmap);
        }
        return JSON.toJSONString(result);
    }

    private String getUrl(String s){
        s = s.substring(s.lastIndexOf("."));
        switch (s){
            case ".doc":
                return "/images/docImg/word.png";
            case ".docx":
                return "/images/docImg/word.png";
            case ".pdf":
                return "/images/docImg/pdf.png";
            case ".txt":
                return "/images/docImg/text.png";
            case ".xls":
                return "/images/docImg/excel.png";
            case ".xlsx":
                return "/images/docImg/excel.png";
            case ".jpg":
                return "/images/docImg/image.png";
            case ".png":
                return "/images/docImg/image.png";
            case ".chm":
                return "/images/docImg/chm.png";
        }
        return "/images/docImg/text.png";
    }

    @RequestMapping("springDocFolder")
    public void openFolder(String path){
        this.openFile(SystemWaiter.getFilesRootPath()+path);
    }

    @RequestMapping("jdkQuickInstall")
    public String jdkQuickInstall(){
        String batPath = "\\modular\\java\\qucikly_jdk\\qucikly_install_jdk.bat";
        List<String> list = new ArrayList<>(10);
        list.add(SystemWaiter.getFilesRootPath()+batPath);
        LocalCommand.execCmd(list);
        return JsonResult.toSuccess();
    };

    @RequestMapping("jdkInstall")
    public String jdkInstall(String version){
        String jdkPath = "\\modular\\java\\qucikly_jdk\\jdk-8u141-windows-x64.exe";
        if("7".equals(version)){
            jdkPath = "\\modular\\java\\qucikly_jdk\\jdk-7u3-windows-x64.exe";
        }else if("6".equals(version)){
            jdkPath = "\\modular\\java\\qucikly_jdk\\jdk-6u43-windows-x64.exe";
        }
        List<String> list = new ArrayList<>(10);
        list.add(SystemWaiter.getFilesRootPath()+jdkPath);
        LocalCommand.execCmd(list);
        return JsonResult.toSuccess();
    };

    @RequestMapping("openJdkEnvironmentTxt")
    public String openJdkEnvironmentTxt(String version){
        String path = "modular/java/qucikly_jdk/jdk_environment.txt";
        SystemWaiter.openBrowser("file://"+SystemWaiter.getFilesRootPath()+path);
        return JsonResult.toSuccess();
    };
}
